package cn.zjitc.quickstart.user.servlet;

import cn.zjitc.quickstart.user.dao.UserDao;
import cn.zjitc.quickstart.user.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录Servlet
 * 处理用户登录请求
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码
        request.setCharacterEncoding("UTF-8");
        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserDao userDao = new UserDao();
        User user = userDao.findUserByUsernameAndPassword(username, password);
        if (user != null) {
            // 登录成功，设置用户信息到session
            request.getSession().setAttribute("user", user);
            //转发
            request.getRequestDispatcher("/successServlet").forward(request,response);
        } else {
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
